import React, { useState } from 'react';
import { Upload, Button, message, Progress } from 'antd';
import { Link } from 'react-router-dom';
import { ArrowLeftOutlined, UploadOutlined, SwapOutlined, DownloadOutlined } from '@ant-design/icons';

// LightPDF API 配置
const API_KEY = 'wxeqbtltm5qhvyalx';
const API_URL = 'https://techhk.aoscdn.com/api/tasks/document/conversion';

const PdfTool = () => {
  const [fileList, setFileList] = useState([]);
  const [converting, setConverting] = useState(false);
  const [progress, setProgress] = useState(0);
  const [convertedFile, setConvertedFile] = useState(null);

  const beforeUpload = (file) => {
    const isPDF = file.type === 'application/pdf';
    const isWord = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                   file.type === 'application/msword';
    
    if (!isPDF && !isWord) {
      message.error('只支持 PDF 或 Word 文件!');
      return false;
    }

    if (file.size > 10 * 1024 * 1024) {
      message.error('文件大小不能超过 10MB!');
      return false;
    }

    setFileList([file]);
    setConvertedFile(null);
    setProgress(0);
    return false;
  };

  // 轮询任务状态
  const pollTaskStatus = async (taskId) => {
    let attempts = 0;
    const maxAttempts = 30; // 30秒
    const interval = 1000; // 1秒

    while (attempts < maxAttempts) {
      try {
        const response = await fetch(`${API_URL}/${taskId}`, {
          headers: {
            'X-API-KEY': API_KEY
          }
        });

        if (!response.ok) {
          throw new Error('Failed to get task status');
        }

        const data = await response.json();
        console.log('Poll response:', data);

        if (data.status === 200) {
          const taskData = data.data;
          
          // 检查任务是否完成
          if (taskData.state === 1 && taskData.file) {
            // 如果任务完成且有文件，直接下载
            const fileResponse = await fetch(taskData.file);
            if (!fileResponse.ok) {
              throw new Error('下载文件失败');
            }
            
            // 返回文件内容和元数据
            return {
              blob: await fileResponse.blob(),
              metadata: {
                pages: taskData.file_pages,
                inputSize: taskData.input_size,
                outputSize: taskData.output_size
              }
            };
          } else if (taskData.state === -1) {
            throw new Error('转换失败');
          }
        }

        // 更新进度
        setProgress(20 + Math.min(60, attempts * 2));
        
        // 等待1秒
        await new Promise(resolve => setTimeout(resolve, interval));
        attempts++;
      } catch (error) {
        console.error('Poll error:', error);
        throw error;
      }
    }

    throw new Error('转换超时，请重试');
  };

  const startConversion = async (file, targetFormat) => {
    try {
      // 1. 上传文件并创建任务
      const formData = new FormData();
      formData.append('file', file);
      formData.append('format', targetFormat);
      formData.append('platform', 'web');

      console.log('Starting conversion to', targetFormat);
      const response = await fetch(API_URL, {
        method: 'POST',
        headers: {
          'X-API-KEY': API_KEY
        },
        body: formData
      });

      if (!response.ok) {
        const error = await response.text();
        throw new Error(`Failed to start conversion: ${error}`);
      }

      const data = await response.json();
      console.log('Start response:', data);

      if (data.status !== 200) {
        throw new Error(data.message || '创建任务失败');
      }

      setProgress(20);

      // 2. 轮询任务状态并获取文件内容
      const result = await pollTaskStatus(data.data.task_id);
      setProgress(80);

      const fileName = file.name.replace(
        targetFormat === 'pdf' ? '.docx' : '.pdf',
        targetFormat === 'pdf' ? '.pdf' : '.docx'
      );
      
      const convertedFile = new File([result.blob], fileName, {
        type: targetFormat === 'pdf' ? 
          'application/pdf' : 
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      });
      
      setConvertedFile(convertedFile);
      setProgress(100);
      
      // 显示转换信息
      message.success(
        `转换成功！文件页数：${result.metadata.pages}，` +
        `原始大小：${(result.metadata.inputSize / 1024).toFixed(1)}KB，` +
        `转换后大小：${(result.metadata.outputSize / 1024).toFixed(1)}KB`
      );
    } catch (error) {
      message.error(error.message || '转换失败，请重试');
      console.error('Conversion error:', error);
    }
  };

  const handleConvert = async () => {
    if (fileList.length === 0) {
      message.error('请先上传文件');
      return;
    }

    setConverting(true);
    setProgress(0);
    const file = fileList[0];
    const isPDF = file.type === 'application/pdf';

    try {
      if (isPDF) {
        await startConversion(file, 'docx');
      } else {
        await startConversion(file, 'pdf');
      }
    } finally {
      setConverting(false);
    }
  };

  const handleDownload = () => {
    if (!convertedFile) {
      message.error('没有可下载的文件');
      return;
    }

    const url = URL.createObjectURL(convertedFile);
    const a = document.createElement('a');
    a.href = url;
    a.download = convertedFile.name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const onRemove = () => {
    setFileList([]);
    setConvertedFile(null);
    setProgress(0);
  };

  return (
    <div className="tool-container">
      <div className="tool-header">
        <Link to="/" className="back-button">
          <ArrowLeftOutlined />
          返回工具箱
        </Link>
        <div className="tool-title">PDF/Word 转换工具</div>
        <div className="tool-description">
          支持 PDF 转 Word 和 Word 转 PDF，文件大小限制 10MB
        </div>
      </div>
      
      <div className="tool-content">
        <div className="conversion-container">
          <Upload
            beforeUpload={beforeUpload}
            onRemove={onRemove}
            fileList={fileList}
            maxCount={1}
            accept=".pdf,.doc,.docx"
          >
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>

          {fileList.length > 0 && (
            <>
              <Button
                type="primary"
                onClick={handleConvert}
                loading={converting}
                icon={<SwapOutlined />}
                style={{ marginTop: 16 }}
              >
                {fileList[0]?.type === 'application/pdf' ? 'PDF转Word' : 'Word转PDF'}
              </Button>

              {progress > 0 && (
                <Progress
                  percent={progress}
                  status={progress === 100 ? 'success' : 'active'}
                  style={{ marginTop: 16, width: '100%', maxWidth: 300 }}
                />
              )}

              {convertedFile && (
                <Button
                  type="primary"
                  onClick={handleDownload}
                  icon={<DownloadOutlined />}
                  style={{ marginTop: 16 }}
                >
                  下载转换后的文件
                </Button>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default PdfTool;
